package com.zhiwang.planet.ui.main


import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.Rect
import android.graphics.drawable.AnimationDrawable
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.RecyclerView
import com.zhiwang.planet.App
import com.zhiwang.planet.R
import com.zhiwang.planet.databinding.FragmentMainBinding
import com.zhiwang.planet.di.ComponentProvider
import com.zhiwang.planet.di.component.DaggerMainComponent
import com.zhiwang.planet.di.component.MainComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.event.NetWorkConnectedEvent
import com.zhiwang.planet.event.RegisterEvent
import com.zhiwang.planet.event.ShowGuideEvent
import com.zhiwang.planet.mvvm.model.entity.main.HomeRecommend
import com.zhiwang.planet.mvvm.viewmodel.ShareViewModel
import com.zhiwang.planet.mvvm.viewmodel.main.MainFactory
import com.zhiwang.planet.mvvm.viewmodel.main.MainViewModel
import com.zhiwang.planet.mvvm.viewmodel.main.sharedViewModels
import com.zhiwang.planet.ui.BaseFragment
import com.zhiwang.planet.ui.FragmentChangeListener
import com.zhiwang.planet.ui.WebViewActivity
import com.zhiwang.planet.util.Store
import com.zhiwang.planet.util.TokenManager
import com.zhiwang.planet.util.androidSchedule
import com.zhiwang.planet.util.dp
import com.zhiwang.planet.widget.explode.ExplosionField
import com.zhiwang.planet.widget.highlight.CenterPosCallback
import com.zhiwang.planet.widget.highlight.HighLight
import com.zhiwang.planet.widget.highlight.position.BottomRightPosCallBack
import com.zhiwang.planet.widget.highlight.position.OnBottomPosCallback
import com.zhiwang.planet.widget.highlight.shape.CircleLightShape
import com.zhiwang.planet.widget.highlight.shape.NoneShape
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_main.*
import kotlinx.android.synthetic.main.layout_diamond.*
import kotlinx.android.synthetic.main.mayday_vip_dialog.view.*
import kotlinx.android.synthetic.main.register_red_packet_alert.view.*
import kotlinx.android.synthetic.main.register_red_packet_alert.view.close
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.concurrent.TimeUnit
import javax.inject.Inject


class MainFragment : BaseFragment() {

    private val TAG = "MainFragment"


//    @Inject
//    lateinit var factory :MainFactory

    @Inject
     lateinit var mainViewModel: MainViewModel

    val sharedViewModel by sharedViewModels<ShareViewModel>()


    lateinit var statusBarHandler: FragmentChangeListener

    var disposable: Disposable? = null


    var recommendGames = ArrayList<HomeRecommend>()

    var currIndex = -1


    val explodeField: ExplosionField by lazy {
        return@lazy ExplosionField.attach2Window(requireActivity())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DaggerMainComponent.builder()
                .appComponent(getAppComponent())
                .accountModule(AccountModule(requireActivity() as AppCompatActivity))
                .autoDisposeModule(AutoDisposeModule(this))
                .build()
                .inject(this)
        mainViewModel.authView = this
        EventBus.getDefault().register(this)

//        mainViewModel= ViewModelProviders.of(this,factory).get(MainViewModel::class.java)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment

        val view = layoutInflater.inflate(R.layout.fragment_main, container, false)
        val binding = DataBindingUtil.bind<FragmentMainBinding>(view)
        binding?.lifecycleOwner = this
        binding?.mainViewModel = mainViewModel
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        sharedViewModel.loggedOut.observe(viewLifecycleOwner, Observer { logout ->
            if (logout)
                mainViewModel.clear()
        })

        mainViewModel.recommendGames.observe(viewLifecycleOwner, Observer {
            if (recommendGames.isEmpty()) {
                recommendGames.addAll(it)
                nextRecommend(currIndex != -1)
            }

        })

//        sharedViewModel.mainTabActive.observe(viewLifecycleOwner, Observer {
//
//        })
    }


    private fun showMayDayVipDialog() {


        val root = layoutInflater.inflate(R.layout.mayday_vip_dialog, null)

        root.view_detail_btn.setOnClickListener {
            WebViewActivity.load(requireContext(), Store.URL_MEMBER_SHIP)
        }

        val dialog = AlertDialog.Builder(requireActivity())
                .setView(root)
                .create()
        dialog.show()

        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))


        root.close.setOnClickListener {
            dialog.dismiss()
        }
    }


    /**
     * 是否需要动画
     */
    fun nextRecommend(animation: Boolean) {
        if (recommendGames.isEmpty()) return

        var animated = true
        when {
            currIndex == -1 -> {//第一次显示，不需要动画
                currIndex++
                animated = false
            }
            currIndex >= recommendGames.lastIndex -> currIndex = 0
            else -> currIndex++
        }

        val game = recommendGames[currIndex]


        if (animated && sharedViewModel.mainTabActive.value == true) {

            game_diamond?.apply {
                if (isHidden.not())
                    explodeField.explode(this) {
                        mainViewModel.currRecommendGame.set(game)
                    }
            }
        } else mainViewModel.currRecommendGame.set(game)

        scheduleNext()

    }

    @SuppressLint("CheckResult")
    private fun scheduleNext() {
        Observable.just(0)
                .delay(8, TimeUnit.SECONDS)
                .androidSchedule()
                .subscribe(object : io.reactivex.Observer<Int> {
                    var d: Disposable? = null
                    override fun onComplete() {

                    }

                    override fun onSubscribe(d: Disposable) {
                        this.d = d
                    }

                    override fun onNext(t: Int) {
                        d?.dispose()
                        nextRecommend(currIndex != -1)
                    }

                    override fun onError(e: Throwable) {

                    }

                })
    }



    var highLight: HighLight? = null
    var highLightSignal = false

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMainPageDataLoadAndShowGuide(event: ShowGuideEvent) {
        highLightSignal = true
    }

    var registerDialog: AlertDialog? = null

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onRegisterSuccess(event: RegisterEvent) {
        val view = layoutInflater.inflate(R.layout.register_red_packet_alert, null)

        view.tv_iknow.setOnClickListener {
            registerDialog?.dismiss()
        }
        view.close.setOnClickListener { registerDialog?.dismiss() }

        registerDialog = AlertDialog.Builder(requireContext())
                .setView(view)
                .create()

        registerDialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

        registerDialog?.show()

        registerDialog?.window?.setDimAmount(0.8f)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNetWorkReconnected(event: NetWorkConnectedEvent) {
        mainViewModel.start()
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        statusBarHandler = context as FragmentChangeListener
    }


    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            mainViewModel.start()
            com.zhiwang.planet.util.Utils.setStatusBar(activity, false, true)
        }
    }

    override fun onResume() {
        super.onResume()
        // 由于在onViewCreated 里面也 调用了 start ，可能因此造成闪烁
        mainViewModel.start()



    }


    override fun onDestroy() {
        super.onDestroy()
        if (disposable != null && disposable?.isDisposed!!.not())
            disposable!!.dispose()
        mainViewModel.dispose()
        EventBus.getDefault().unregister(this)
    }

}
